package gpl.pierrick.brihaye.aramorph;

import gpl.pierrick.brihaye.util.Pair;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.logging.Logger;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

public class InMemoryCompatibilityTable implements CompatibilityTable{
	/**A logger to write log messages*/
	private static Logger logger = Logger.getLogger(InMemoryCompatibilityTable.class.getName());

	/**Name of this table in the database*/
	protected final String tableName;

	/**A set of all entries of this compatibility table*/
	protected Collection<Pair> entries;
	
	/**
	 * Constructs a new Compatibility table with the given name
	 * @param tableName
	 */
	public InMemoryCompatibilityTable(String tableName) {
		this.tableName = tableName;
		this.entries = new HashSet<Pair>();
	}
	
	/**Stores maximum length for entries*/
	private int maxEntry;
	
	public boolean contains(String first, String second) {
		return entries.contains(new Pair(first.trim(),second.trim()));
	}

	/**
	 * Adds the given pair to the table
	 * @param first first part of entry
	 * @param second second part of entry
	 */
	public void addCompatabilityEntry(String first, String second) {
		entries.add(new Pair(first,second));
	}

	/**
	 * Write down some statistical results collected during loading
	 */
	public void writeStatistics() {
		logger.info("Statistics for compatibility table");
		logger.info("Maximum length:"+maxEntry);
	}
	
	/**
	 * Loads a compatibility table from an XML file.
	 * The XML file is already open and its input stream is passed.
	 * @param is the input stream for the XML file.
	 * @return the Compatibility table that has been loaded.
	 */
	public void loadFromXML(InputStream is) {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		factory.setValidating(false);
		try {
			SAXParser sax = factory.newSAXParser();
			XMLCompatibilityLoader cl = new XMLCompatibilityLoader(this);
			sax.parse(is,cl);
			//write down statistical results
			writeStatistics();
		} catch (ParserConfigurationException pce) {
			logger.warning("Could not create that parser.");
			logger.warning(pce.getMessage());
		} catch (SAXException se) {
			logger.warning("Problem with the SAX parser");
			logger.warning(se.getMessage());
		} catch (IOException ioe) {
			logger.warning("Error reading file.");
			logger.warning(ioe.getMessage());
		}
	}

	public void loadFromDB(DBManager readonlyConnection) {
		readonlyConnection.getAllEntris(tableName, this.entries);
	}
}
